@extends('buy_process.master')

@section('title')
    创建订单-Craft
@endsection

@section('link')
    <link rel="stylesheet" href="{{asset('/css/buy_process/createOrder.css')}}">
@endsection

@section('headerTitle')
    创建订单
@endsection


@section('content')
    <section id="app" style="margin-top: 50px;padding-bottom: 50px">
        <el-row>
            <el-col :span="18" :offset="3">
                <el-row>
                    <el-col :span="24">
                        <el-steps :active="orderStatus">
                            <el-step title="下单" icon="el-icon-tickets"></el-step>
                            <el-step title="支付" icon="el-icon-coin"></el-step>
                            <el-step title="下单成功" icon="el-icon-circle-check"></el-step>
                        </el-steps>
                    </el-col>
                </el-row>

                <el-row :gutter="50" style="margin-top: 50px">

                    <el-col :span="10">
                        <el-image class="crafts-item-img" :src="'{{asset('/')}}'+craft.imgUrl"
                                  @click="detail"></el-image>
                    </el-col>


                    <el-col :span="11" :offset="1" class="orderInfo">
                        <el-form :model="useAddress" label-position="top">
                            <el-form-item label="收货人地址" class="address">
                                <el-row v-show="useAddressVisible">
                                    <div class="useAddress-item">@{{ useAddress.name }}</div>
                                    <div class="useAddress-item">@{{ useAddress.phone }}</div>
                                    <div class="useAddress-item">
                                        @{{ useAddress.province }} |
                                        @{{ useAddress.city }} |
                                        @{{ useAddress.county }} |
                                        @{{ useAddress.region }}
                                    </div>
                                    <div class="useAddress-item">@{{ useAddress.detail_address }}</div>
                                </el-row>
                                <el-row :gutter="20" style="margin-top: 10px">
                                    <el-col :span="12">
                                        <el-button @click="addressDialogVisible=true"
                                                   :disabled="myAddresses.length ===0">选择地址
                                        </el-button>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-button @click="openAddressDrawer('add')">使用新地址</el-button>
                                    </el-col>
                                </el-row>
                            </el-form-item>

                            <el-form-item label="作品信息">
                                <div>@{{ craft.name }}</div>
                                <div>@{{ craft.author }}</div>
                                <div>￥ @{{ craft.price }} | @{{ craft.size }} </div>
                            </el-form-item>

                            <el-form-item label="备注">
                                <el-input type="textarea" v-model="remark"
                                          placeholder="如果您特殊的需求，请在这里写下">
                                </el-input>
                            </el-form-item>


                            <el-form-item label="合计">
                               <div>￥ @{{ craft.price }}</div>
                            </el-form-item>

                            <el-form-item>
                                <el-button @click="submitOrder" class="btn_submit_order"
                                           :disabled="!useAddressVisible">
                                    提交订单
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </el-col>
                </el-row>
            </el-col>
        </el-row>


        <el-dialog title="我的收货地址" :visible.sync="addressDialogVisible" class="myAddressDialog">
            <a v-for="(item,index) in myAddresses" :key="item.id"
               @click="selectMyAddress(item)">
                <el-row class="location_box">
                    <el-col :sm="22" :xs="22" :md="22" :offset="1">
                        <el-row>
                            <el-col class="location">
                                @{{item.province}} |
                                @{{item.city}} |
                                @{{item.county}} |
                                @{{item.region}} |
                                @{{item.phone}} |
                                —— @{{ item.name }}
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col class="detail-address">
                                @{{ item.detail_address}}
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
            </a>
        </el-dialog>

        <el-drawer
            :with-header="false"
            direction="rtl"
            :modal="false"
            ref="drawer"
            :visible.sync="addressDrawerVisible"
            class="drawer_address">

            <el-form class="select_box" label-width="150px"
                     :model="selectAddress" ref="form-address" :rules="rules"
                     :hide-required-asterisk="true">
                <el-form-item label="收货人" prop="name">
                    <el-input v-model="selectAddress.name" placeholder="收货人姓名"></el-input>
                </el-form-item>

                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="selectAddress.phone" placeholder="收货人联系电话"></el-input>
                </el-form-item>


                <el-form-item label="请选择省市/地区" prop="selectProvince">
                    <el-select v-model="selectAddress.selectProvince" placeholder="请选择省市/地区" @change="provinceChange">
                        <el-option
                            v-for="item in provinces"
                            :key="item.province_id"
                            :label="item.province_name"
                            :value="item.province_id">
                        </el-option>
                    </el-select>
                </el-form-item>


                <el-form-item label="请选择城市/地区" prop="selectCity">
                    <el-select v-model="selectAddress.selectCity" placeholder="请选择城市/地区" :disabled="cityEnable"
                               @change="cityChange">
                        <el-option
                            v-for="item in cities"
                            :key="item.city_id"
                            :label="item.city_name"
                            :value="item.city_id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="请选择城镇/地区" prop="selectCounty">
                    <el-select v-model="selectAddress.selectCounty" placeholder="请选择城镇/地区" :disabled="countyEnable"
                               @change="countyChange">
                        <el-option
                            v-for="item in counties"
                            :key="item.county_id"
                            :label="item.county_name"
                            :value="item.county_id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="请选择地区" prop="selectRegion">
                    <el-select v-model="selectAddress.selectRegion" placeholder="请选择地区" :disabled="regionEnable"
                               @change="regionChange">
                        <el-option
                            v-for="item in regions"
                            :key="item.town_id"
                            :label="item.town_name"
                            :value="item.town_id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="详细地址" prop="detailAddress">
                    <el-input class="inp-detailed-address" type="textarea" placeholder="请填写详细地址"
                              v-model="selectAddress.detailAddress">
                    </el-input>
                </el-form-item>

                <el-form-item v-if="myAddresses.length<5">
                    <el-checkbox v-model="autoSyncInAddress">同步到我的地址</el-checkbox>
                </el-form-item>

                <el-form-item>
                    <el-button @click="closeDrawer" class="btn_close">关 闭</el-button>
                    <el-button @click="drawerSubmit" class="btn_confirm">确 定</el-button>
                </el-form-item>

            </el-form>

        </el-drawer>
    </section>
@endsection

@section('js')
    <script>
        var app = new Vue({
            el: '#app',
            created() {
                if (this.myAddresses.length > 0) {
                    let item = this.myAddresses[0];
                    this.useAddress.name = item.name;
                    this.useAddress.phone = item.phone;
                    this.useAddress.province = item.province;
                    this.useAddress.city = item.city;
                    this.useAddress.county = item.county;
                    this.useAddress.town_id = item.region_id;
                    this.useAddress.region = item.region;
                    this.useAddress.detail_address = item.detail_address;
                    this.useAddressVisible = true;
                }
            },
            data() {
                var checkPhone = (rule, value, callback) => {
                    const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
                    if (value === '') {
                        callback(new Error('请输入电话号码'));
                    } else if (!reg.test(value)) {
                        callback(new Error('请输入正确的11位手机号码'));
                    } else {
                        callback();
                    }
                };
                return {
                    user:@json(Auth::user()),
                    craft:@json($data).craft,  //当前作品
                    myAddresses:@json($data).address,  //我的所有地址
                    optionOfAddress: 'add', //add为添加地址，’edit为修改地址‘
                    addressDialogVisible: false,  //是否显示地址选择dialog
                    addressDrawerVisible: false,  //是否显示地址添加修改drawer
                    useAddressVisible: false,//显示要使用的地址信息  true显示 false不显示  代表未填写相应信息
                    orderStatus: 0,  //步骤条

                    useAddress: {
                        province: '',
                        city: '',
                        county: '',
                        region: '',
                        detail_address: '',//详细地址
                        town_id: '', //即region_id
                        name: '',   //收货人姓名
                        phone: ''//收货人联系电话
                    },
                    remark: '',//备注


                    drawerOption: '',//add代表添加地址 edit代表修改地址
                    autoSyncInAddress: false,//是否同步添加到我的地址
                    provinces: (@json($data)).provinces,
                    cities: [],
                    counties: [],
                    regions: [],
                    cityEnable: true,
                    countyEnable: true,
                    regionEnable: true,
                    selectAddress: {
                        phone: '',
                        name: '',
                        selectProvince: '',
                        selectCity: '',
                        selectCounty: '',
                        selectRegion: '',
                        detailAddress: '',
                        currentId: ''
                    },
                    selectProvinceName: '',
                    selectCityName: '',
                    selectCountyName: '',
                    selectRegionName: '',
                    rules: {
                        name: [{required: true, message: '收货人不能为空', trigger: ['blur', 'change']}],
                        phone: [{validator: checkPhone, trigger: ['blur', 'change']}],
                        selectProvince: [{required: true, message: '请选择省市/地区', trigger: ['blur', 'change']}],
                        selectCity: [{required: true, message: '请选择城市/地区', trigger: ['blur', 'change']}],
                        selectCounty: [{required: true, message: '请选择城镇/地区', trigger: ['blur', 'change']}],
                        selectRegion: [{required: true, message: '请选择地区', trigger: ['blur', 'change']}],
                        detailAddress: [{required: true, message: '详细地址不能为空', trigger: ['blur', 'change']}],
                    }
                }
            },
            methods: {
                submitOrder() {
                    let data=new FormData();
                    data.append('town_id',this.useAddress.town_id);
                    data.append('goods_id',this.craft.id);
                    data.append('name',this.useAddress.name);
                    data.append('phone',this.useAddress.phone);
                    data.append('detail_address',this.useAddress.detail_address);
                    data.append('remark',this.remark);
                    axios.post('/order/create',data)
                        .then(res=>{
                            if(res.data.status_code===200){
                                window.location='/order/pay/'+res.data.data.orderId;
                            }else{
                                app.noticeWarnings(res.data.error);
                            }
                        })
                        .catch(err=>{
                            console.log(err);
                            app.noticeError('服务器繁忙，请稍后再试！');
                        })
                },
                selectMyAddress(item) {
                    this.useAddress.name = item.name;
                    this.useAddress.phone = item.phone;
                    this.useAddress.province = item.province;
                    this.useAddress.city = item.city;
                    this.useAddress.county = item.county;
                    this.useAddress.town_id = item.region_id;
                    this.useAddress.region = item.region;
                    this.useAddress.detail_address = item.detail_address;
                    this.useAddressVisible = true;
                    this.addressDialogVisible = false;
                },
                openAddressDrawer(option) {
                    //清空输入框
                    if (option === 'add') {
                        app.selectAddress.name = '';
                        app.selectAddress.phone = '';
                        app.selectAddress.selectProvince = '';
                        app.selectAddress.selectCity = '';
                        app.selectAddress.selectCounty = '';
                        app.selectAddress.selectRegion = '';
                        app.selectAddress.detailAddress = '';
                        app.selectAddress.currentId = '';
                        app.selectProvinceName = '';
                        app.selectCityName = '';
                        app.selectCountyName = '';
                        app.selectRegionName = '';
                    } else if (option === 'edit') {
                        app.selectAddress.name = item.name;
                        app.selectAddress.phone = item.phone;
                        app.selectAddress.detailAddress = item.detail_address;
                        app.provinceChange(item.province_id);
                        app.cityChange(item.city_id);
                        app.countyChange(item.county_id);
                        app.selectAddress.selectProvince = item.province_id;
                        app.selectAddress.selectCity = item.city_id;
                        app.selectAddress.selectCounty = item.county_id;
                        app.selectAddress.selectRegion = item.region_id;
                        app.selectAddress.currentId = item.id;
                        app.currentIndex = index;
                        app.selectProvinceName = item.province;
                        app.selectCityName = item.city;
                        app.selectCountyName = item.county;
                        app.selectRegionName = item.region;
                    }
                    app.drawerOption = option;
                    app.autoSyncInAddress = false;
                    app.addressDrawerVisible = true;
                },
                closeDrawer() {
                    app.selectAddress.selectProvince = '';
                    app.cityEnable = true;
                    app.countyEnable = true;
                    app.regionEnable = true;
                    app.selectAddress.selectCity = '';
                    app.selectAddress.selectCounty = '';
                    app.selectAddress.selectRegion = '';
                    app.addressDrawerVisible = false;
                },
                //使用新地址
                drawerSubmit() {
                    let check = false;
                    this.$refs['form-address'].validate(result => {
                        check = result;
                    });
                    if (!check) {
                        this.noticeWarning('请将数据填写完整！');
                        return false;
                    }
                    //如果操作为添加 且勾选了同步到我的地址 则将地址添加到我的地址中
                    if (app.drawerOption === 'add' && app.autoSyncInAddress) {
                        let data = new FormData();
                        data.append('name', app.selectAddress.name);
                        data.append('phone', app.selectAddress.phone);
                        data.append('province_id', app.selectAddress.selectProvince);
                        data.append('province', app.selectProvinceName);
                        data.append('city_id', app.selectAddress.selectCity);
                        data.append('city', app.selectCityName);
                        data.append('county_id', app.selectAddress.selectCounty);
                        data.append('county', app.selectCountyName);
                        data.append('region_id', app.selectAddress.selectRegion);
                        data.append('region', app.selectRegionName);
                        data.append('detail_address', this.selectAddress.detailAddress);
                        data.append('user_id', app.user.id);
                        axios.post('/user/myAddress/add', data)
                            .then(res => {
                                if (res.data.status_code === 200) {
                                    app.myAddresses.push(res.data.data);
                                    app.drawer_AddressVisible = false;
                                    app.noticeSuccess('新地址已同步到您的地址中');
                                } else {
                                    app.noticeWarnings(res.data.error);
                                }
                            })
                            .catch(err => {
                                app.noticeError('哦豁！服务器出BUG了!GG，请刷新重试！');
                                console.log(err)
                            })
                    }

                    this.useAddress.name = this.selectAddress.name;
                    this.useAddress.phone = this.selectAddress.phone;
                    this.useAddress.province = this.selectProvinceName;
                    this.useAddress.city = this.selectCityName;
                    this.useAddress.county = this.selectCountyName;
                    this.useAddress.town_id = this.selectAddress.selectRegion;
                    this.useAddress.region = this.selectRegionName;
                    this.useAddress.detail_address = this.selectAddress.detailAddress;
                    this.useAddressVisible = true;
                    this.addressDrawerVisible = false;
                },


                provinceChange(selectItem) {
                    app.selectAddress.selectProvince = selectItem;
                    this.cities = [];
                    this.selectAddress.selectCity = '';
                    this.selectAddress.selectCounty = '';
                    this.selectAddress.selectRegion = '';
                    this.countyEnable = true;
                    this.regionEnable = true;
                    for (let i = 0; i < this.provinces.length; i++) {
                        if (this.provinces[i].province_id === selectItem) {
                            app.selectProvinceName = this.provinces[i].province_name;
                            break;
                        }
                    }
                    axios.get('/user/getCity/' + selectItem)
                        .then(res => {
                            res.data.data.forEach((item, index) => {
                                app.cities.push(item);
                            });
                            app.cityEnable = false;
                        })
                        .catch(err => {
                            app.noticeError('获取城市数据失败，请刷新重试！');
                            console.log(err);
                        })
                },
                cityChange(selectItem) {
                    app.selectAddress.selectCity = selectItem;
                    this.counties = [];
                    this.selectAddress.selectCounty = '';
                    this.selectAddress.selectRegion = '';
                    this.regionEnable = true;
                    for (let i = 0; i < this.cities.length; i++) {
                        if (this.cities[i].city_id === selectItem) {
                            app.selectCityName = this.cities[i].city_name;
                            break;
                        }
                    }
                    axios.get('/user/getCounty/' + selectItem)
                        .then(res => {
                            res.data.data.forEach((item, index) => {
                                app.counties.push(item);
                            });
                            app.countyEnable = false;
                        })
                        .catch(err => {
                            app.noticeError('获取城镇数据失败，请刷新重试！');
                            console.log(err);
                        })
                },
                countyChange(selectItem) {
                    app.selectAddress.selectCounty = selectItem;
                    this.regions = [];
                    this.selectAddress.selectRegion = '';
                    for (let i = 0; i < this.counties.length; i++) {
                        if (this.counties[i].county_id === selectItem) {
                            app.selectCountyName = this.counties[i].county_name;
                            break;
                        }
                    }

                    axios.get('/user/getRegion/' + selectItem)
                        .then(res => {
                            res.data.data.forEach((item, index) => {
                                app.regions.push(item);
                            });
                            app.regionEnable = false;
                        })
                        .catch(err => {
                            app.noticeError('获取地区数据失败，请刷新重试！');
                            console.log(err);
                        })
                },
                regionChange(selectItem) {
                    app.selectAddress.selectRegion = selectItem;
                    for (let i = 0; i < this.regions.length; i++) {
                        if (this.regions[i].town_id === selectItem) {
                            app.selectRegionName = this.regions[i].town_name;
                            break;
                        }
                    }
                },
                detail() {
                    window.location = '/detail/' + this.craft.id;
                },
                noticeWarning(message) {
                    app.$notify.warning({
                        title: '提示',
                        message: message,
                    });
                },
                noticeSuccess(message) {
                    app.$notify.success({
                        title: '提示',
                        message: message,
                    });
                },
                noticeWarnings(messages) {
                    messages.forEach((item, index) => {
                        setTimeout(function () {
                            app.$notify.warning({
                                title: '提示',
                                message: item,
                            });
                        }, 1)
                    })
                },
                noticeError(message) {
                    app.$notify.error({
                        title: '提示',
                        message: message,
                    });
                }
            },
        })
    </script>
@endsection
